package com.dinggao.crossgo.module.roadbook.activity;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.dinggao.crossgo.R;
import com.dinggao.crossgo.core.base.BaseActivity;
import com.dinggao.crossgo.core.constant.CommonConstant;
import com.dinggao.crossgo.core.manage.ApiManager;
import com.dinggao.crossgo.core.paser.FastJsonUtils;
import com.dinggao.crossgo.core.util.LogUtils;
import com.dinggao.crossgo.core.util.SharedPreferencesUtil;
import com.dinggao.crossgo.core.util.ToastUtil;
import com.dinggao.crossgo.module.roadbook.adapter.ParentDetailsAdapter;
import com.dinggao.crossgo.module.roadbook.data.ParentDetailsBean;
import com.dinggao.crossgo.module.roadbook.data.RoadBookLeftBean;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RoadBookParentDetailsActivity extends BaseActivity {

    public static final String TAG = "RoadBookParent";

    @BindView(R.id.parent_details_recycler)
    RecyclerView parentDetailsRecycler;
    @BindView(R.id.parent_mapview)
    MapView mMapView;
    @BindView(R.id.iv_top_bar_left)
    ImageView ivTopBarLeft;
    @BindView(R.id.tv_top_bar_title)
    TextView tvTopBarTitle;
    @BindView(R.id.iv_top_bar_right)
    ImageView ivTopBarRight;
    @BindView(R.id.image_empty)
    ImageView imageEmpty;
    @BindView(R.id.headimage)
    ImageView headImage;
    @BindView(R.id.parent_details_usename)
    TextView parentDetailsUsename;
    @BindView(R.id.parent_details_organization)
    TextView parentDetailsOrganization;
    @BindView(R.id.parent_details_travel)
    TextView parentDetailsTravel;
    private List<ParentDetailsBean.DataBean.RoadBookJournalListBean.ItemsBean> detailsBeansList = new ArrayList<>();
    private ParentDetailsAdapter adapter;
    private List<LatLng> pathList = new ArrayList<>();
    private AMap aMap;
    private Polyline polyline;
    private Marker startMarker, stopMarker;
    private ArrayList<MarkerOptions > markerList = new ArrayList<>();
    private Intent trackIntent;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_road_book_parent_details;
    }

    @Override
    protected void onInitialization(Bundle bundle) {
        mMapView.onCreate(bundle);
        tvTopBarTitle.setText("路书详情");
        ivTopBarRight.setImageDrawable(getResources().getDrawable(R.drawable.road_book_parent_share_icon));
        trackIntent=new Intent(RoadBookParentDetailsActivity.this,RoadBookTrackDetailsActivity.class);

        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 设置卫星地图模式，aMap是地图控制器对象。
        parentDetailsRecycler.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ParentDetailsAdapter(R.layout.item_parent_detail_recycler, detailsBeansList);
        parentDetailsRecycler.setAdapter(adapter);

        parentDetailsRecycler.setHasFixedSize(true);
        parentDetailsRecycler.setNestedScrollingEnabled(false);
        initData();



    }


    private void initData() {
        String accessToken = SharedPreferencesUtil.getSharedPreferencesString(RoadBookParentDetailsActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN);

        LogUtils.e(TAG, accessToken);

        int roadid = getIntent().getExtras().getInt("id");
        OkGo.<String>get(ApiManager.ROADBOOK_GET + roadid)
                .headers("accessToken", accessToken)
                .tag(this)
                .params("limit", "10")
                .params("page", "1")
                .params("roadBookId", roadid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        if (response != null) {
                            LogUtils.e(TAG, response.body());
                            imageEmpty.setVisibility(View.GONE);
                            ParentDetailsBean parentDetailsBean = FastJsonUtils.getObject(response.body(), ParentDetailsBean.class);
                            detailsBeansList.addAll(parentDetailsBean.getData().getRoadBookJournalList().getItems());
                            adapter.notifyDataSetChanged();
                            if (parentDetailsBean.getData() != null) {
                                initInfo(parentDetailsBean.getData());

                            }
                            if (parentDetailsBean.getData().getTrackInfoList().size() > 0) {
                                initMap(parentDetailsBean.getData().getTrackInfoList().get(0).getPath());

                            }
                        } else {

                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e(TAG, response.getException().toString());
                    }
                });
    }

    private void initInfo(ParentDetailsBean.DataBean data) {

        parentDetailsOrganization.setText(data.getCar());
        parentDetailsTravel.setText(data.getTitle());

        String nickName = SharedPreferencesUtil.getSharedPreferencesString(RoadBookParentDetailsActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USERINFO_NICKNAME);

        String headimage = SharedPreferencesUtil.getSharedPreferencesString(RoadBookParentDetailsActivity.this,
                CommonConstant.USERINFO_SHREDPREFERENCE, CommonConstant.USERINFO_HEANDIMAGEURI);

        boolean useWEIXIN = SharedPreferencesUtil.getSharedPreferencesBoolean(RoadBookParentDetailsActivity.this,
                CommonConstant.USERINFO_SHREDPREFERENCE, CommonConstant.USERINFO_USEWEIXIN);


                //设置头像和昵称
        if (useWEIXIN) {
            parentDetailsUsename.setText(nickName);

            Glide.with(this).load(headimage).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headImage);
        } else {
            parentDetailsUsename.setText(data.getCreatorName());
            Glide.with(this).load(getResources().getDrawable(R.mipmap.app_icon)).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headImage);
        }

    }

    private void initMap(List<ParentDetailsBean.DataBean.TrackInfoListBean.PathBean> path) {
        for (int i = 0; i < path.size(); i++) {

            pathList.add(new LatLng(path.get(i).getLatitude(), path.get(i).getLongitude()));

        }
        trackIntent.putExtra("pathList",(Serializable) pathList);

        markerList.add(new MarkerOptions().position(pathList.get(0)));
        markerList.add(new MarkerOptions().position(pathList.get(pathList.size() - 1)));

        aMap.addMarkers(markerList, true);

//                        startMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
//                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.path_start_icon)));
//
//                        startMarker.setPosition(pathList.get(0));
//
//                        stopMarker= aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
//                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.path_end_icon)));
//                        stopMarker.setPosition(pathList.get(pathList.size()-1));

        // 初始化轨迹
        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.width(16);
        polylineOptions.color(Color.parseColor("#ffd219"));
        polyline = aMap.addPolyline(polylineOptions);
        polyline.setPoints(pathList);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @OnClick({R.id.iv_top_bar_left, R.id.iv_top_bar_right,R.id.map_text})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top_bar_left:
                finish();
                break;
            case R.id.iv_top_bar_right:
                break;
            case R.id.map_text:

                if (pathList.size()>0){
                    startActivity(trackIntent);

                }else {
                    ToastUtil.showLong(RoadBookParentDetailsActivity.this,"没有轨迹");
                }
                break;
        }
    }
}
